/*
Copyright (c) [2019年5月1日] [吴超]
[MBT_Studio] is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
		 http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/
#include "stdafx.h"
#include "uiNodeLink.h"

#include <stack>
#include "节点.h"


static std::stack<S_NodeLink*> g_连接线回收站;



S_NodeLink* f_createNodeLink() {
	S_NodeLink* Link = (S_NodeLink*)malloc(sizeof(S_NodeLink));

	*Link = {};
	Link->m_GPU缓存偏移 = -1;

	return Link;
}

S_NodeLink* f_genNodeLink() {
	if (g_连接线回收站.size()) {
		S_NodeLink* l = g_连接线回收站.top();
		(*l) = {};
		g_连接线回收站.pop();
		return l;
	}

	return f_createNodeLink();
}

void f_genMultNodeLink(std::vector<S_NodeLink*>& ls) {
	uint32 num = ls.size();

	for (uint32 i = 0; i < num; ++i) {
		ls[i] = f_genNodeLink();
	}
	
}




void f_NodeLine_回收(S_NodeLink* link) {
	g_连接线回收站.push(link);
}

void f_updateNodeLink(S_NodeLink* link) {

}




uvec2 S_NodeLink::f_断开输出链接() {
	uvec2 插座位置;
	插座位置.x = m_插座in->f_getNode()->f_get输入插座Loc(m_插座in);
	插座位置.y = m_插座out->f_getNode()->f_get输出插座Loc(m_插座out);
	
	//插座位置.x = m_插座out->f_getNode()->f_get输入插座Loc(m_插座out);
	//插座位置.y = m_插座in->f_getNode()->f_get输出插座Loc(m_插座in);

	m_插座in->f_断开输出链接(this);
	m_插座out->f_断开输出链接(this);

	return 插座位置;
}

S_NodeLink* S_NodeLink::f_Link(C_插座基类* m_in, C_插座基类* m_out) {
	S_NodeLink* 要替换的连接线 = nullptr;

	if (m_in->f_接入插座是否匹配(m_out->m_Type)) {
		if (m_in->f_isOut() && m_out->f_isOut()) return 要替换的连接线;
		if (m_in->f_isOut() == false && m_out->f_isOut() == false) return 要替换的连接线;
		//if (m_out->f_接入插座是否匹配(m_in->m_Type) == false) return nullptr;
		if (m_in->f_接入插座是否匹配(m_out->m_Type) == false) return nullptr;


		if (m_in->f_is单链接()) {
			auto& links = m_in->f_getLinkLines();
			if (links.size()) {
				if (links[0]->m_插座in == m_in && links[0]->m_插座out == m_out) {
					return 要替换的连接线;
				}

				要替换的连接线 = links[0];

				要替换的连接线->m_插座in->f_断开输出链接(要替换的连接线);
				要替换的连接线->m_插座out->f_断开输出链接(要替换的连接线);
			}
		}

		m_插座out = m_out;
		m_插座in = m_in;

		m_插座in->f_Link(this);
		m_插座out->f_Link(this);
		m_插座in->f_getNode()->f_set是否要更新(true);
		m_插座in->f_getNode()->f_标记层级结构需更新(true);

		m_插座out->f_getNode()->f_set是否要更新(true);
	}

	if (要替换的连接线) return 要替换的连接线;
	return (S_NodeLink*)0xffffffffffffffff;
}

uvec2 S_NodeLink::f_get链接线插座id() {
	uvec2 r_id = {
		m_插座in->f_getNode()->f_get输入插座Loc(m_插座in),
		m_插座out->f_getNode()->f_get输出插座Loc(m_插座out),
	};
	return r_id;
}


void f_socket_link(C_插座基类* m_插座in, C_插座基类* m_插座out) {
	if (m_插座in->f_get方向() == E_插座方向::e_插座Type_输出) {
		return;
	}
	if (m_插座out->f_get方向() == E_插座方向::e_插座Type_输入) {
		return;
	}
	auto* Link = f_genNodeLink();
	Link->f_Link(m_插座in, m_插座out);
}




